package com.example.wechat.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class GenerateQRCodeUtil {



    /**
     * 生成二维码
     * @param contents 二维码的内容
     * @param width 二维码的宽度，单位是像素
     * @param height 二维码的高度，单位是像素
     * @return 返回二维码BufferedImage
     */
    public static byte[] generateQRCode(String contents,int width,int height) throws Exception {
        Map<EncodeHintType, Object> hints = new HashMap<>();
        //指定MultiFormatWriter().encode的content参数的编码格式
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE,width,height,hints);
        //BitMatrix matrix, String format, Path file
//        Path path= FileSystems.getDefault().getPath("D://","Test/test.jpg");
//        MatrixToImageWriter.writeToPath(bitMatrix,"jpg",path);
        BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage,"jpg",byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] bytes = byteArrayOutputStream.toByteArray();
        return bytes;
    }


}
